package com.nulldev.util.web.nTube.pages;

import static com.nulldev.util.web.nTube.pages.Urlizer.decodeUrlizer;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Map;

import com.nulldev.util.JVM.Arguments;
import com.nulldev.util.VariableAPI.StringsUtil;
import com.nulldev.util.concurrency.threadIt.v4.asyncTasks.AsyncTaskCallback;
import com.nulldev.util.concurrency.threadIt.v4.emapi.cntft.ControllableFutureTask;
import com.nulldev.util.io.IOUtils;
import com.nulldev.util.logging.Logger;
import com.nulldev.util.logging.LoggerFactory;
import com.nulldev.util.web.HttpClient.HttpClient;
import com.nulldev.util.web.HttpClient.HttpResponse;
import com.nulldev.util.web.HttpServer3.Response;
import com.nulldev.util.web.HttpServer3.pages.v3.ASyncHttpPage3;
import com.nulldev.util.web.URLUtils.URLUtils;
import com.nulldev.util.web.nTube.util.DashMPDTranslator;

public class DASHTranslatorPage extends ASyncHttpPage3 {

	private static final Logger log = LoggerFactory.getLoggerD(Arguments.hasArgument("--debug", "--trace"));

	public DASHTranslatorPage() {
		super("/dash_translate/proxyAPI");
	}

	@SuppressWarnings("resource")
	@Override
	public void onFutureRequest(final Request request, final ControllableFutureTask<Response> r) {
		final Map<String, String> s = URLUtils.parseQuery(request.url());
		if (s == null) {
			log.error("Query url failed and returned null!");
			r.complete(new Response(503));
			return;
		} else if ((!s.containsKey("url") && !s.containsKey("uzc"))) {
			log.debug("Dropped DASH-Translate request: No urlizer URL found.");
			log.debug("Got: " + request.url());
			r.complete(new Response(403));
			return;
		}
		final String link = decodeUrlizer(request.url());
		try {
			HttpClient.getStream().url(link).createTaskAndRun().addCallback(new AsyncTaskCallback<HttpResponse<InputStream>>() {

				@Override
				public void onCompletion(final HttpResponse<InputStream> result) {
					if (!result.successful()) {
						r.fail(new RuntimeException("Got status code: " + result.status()));
						IOUtils.closeQuietly(result);
						return;
					}
					final InputStreamReader isr = new InputStreamReader(result.data());
					// FIXME: I fixed this already...not sure if this fix should be here still.
					final String out = StringsUtil.replace(DashMPDTranslator.translate(request, isr), "&nbsp;", "&amp;nbsp;");
					IOUtils.closeQuietly(result);
					r.complete(new Response(200, createStream(out)).header("Content-Length", out.length()));
				}

				@Override
				public void onError(Throwable e) {
					r.fail(e);
				}
			}).waitTillCompletion();
		} catch (Exception e) {
			r.fail(e);
		}
	}

}
